// 获取应用实例
const defaultAvatar = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({
  data: {
    motto: '头像或昵称仅用于排行榜展示',
    userInfo: {
      avatarUrl: '',
      nickName: '',
    },
    app: getApp<IAppOption>()
  },
  onLoad() {
    const { nickName, avatarUrl } = this.data.app.globalData.userInfo as any
    this.setData({ userInfo: { nickName, avatarUrl: avatarUrl || defaultAvatar } })
  },
  // 事件处理函数
  updateUserInfo(data: any) {
    return new Promise((resolve, reject) => {
      const mid = {
        name: this.data.app.globalData.userInfo.openid,
        ...data
      }
      wx.request({
        header: {
          Authorization: this.data.app.globalData.userInfo.token
        },
        url: `https://www.liqiantw.icu:3000/score/avatar`,
        method: 'POST',
        data: mid,
        success: function (response) {
          resolve(response)
        },
        fail: function (error) {
          reject(error)
        }
      });
    })
  },
  onChooseAvatar(e: any) {
    const { avatarUrl } = e.detail
    const base64Avatar = 'data:image/jpg;base64,' + wx.getFileSystemManager().readFileSync(avatarUrl, 'base64')
    this.updateUserInfo({ avatar: base64Avatar }).then(() => {
      this.setData({
        "userInfo.avatarUrl": avatarUrl,
      })
      this.data.app.globalData.userInfo.avatarUrl = avatarUrl
    })

  },
  onInputChange(e: any) {
    const nickName = e.detail.value
    this.updateUserInfo({ nickName }).then(() => {
      this.setData({
        'userInfo.nickName': nickName
      })
    }).catch(err => {
      console.log(err);
    })
  }
})